import 'dart:math';
import 'dart:convert';
import 'package:flutter_lib/utils/LogUtils.dart';
import 'package:get/get.dart';
import 'package:web_socket_channel/html.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

class SimpleWebSocket {
  String _url;
  WebSocketChannel? _socket;
  Function()? onOpen;
  Function(dynamic msg)? onMessage;
  Function(int code, String reaso)? onClose;

  SimpleWebSocket(this._url);

  connect() async {
    Random r = new Random();
    String key = base64.encode(List<int>.generate(8, (_) => r.nextInt(255)));
    print("connect ${_url}  GetPlatform.isWeb:${GetPlatform.isWeb}");
    if(GetPlatform.isWeb){
      _socket = HtmlWebSocketChannel.connect(Uri.parse(_url));
    }else{
      _socket = IOWebSocketChannel.connect(Uri.parse(_url), headers: {
        'Connection': 'Upgrade',
        'Upgrade': 'websocket',
        'Sec-WebSocket-Version': '13',
        'Sec-WebSocket-Key': key.toLowerCase(),
        'Cache-Control': 'no-cache',
        "Pragma": "no-cache",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "en-US,en;q=0.9",
        "Sec-WebSocket-Extensions": "permessage-deflate; client_max_window_bits",
      });
    }

    onOpen?.call();
    _socket!.stream.listen((event) {
      onMessage?.call(event);
    });
  }

  send(data) {
    if (_socket != null) {
      LogUtils.v('send: $data');
      _socket!.sink.add(data);
    }else{
      LogUtils.e('socket null ');
    }
  }

  close() {
    if (_socket != null) _socket!.sink.close();
  }

}



